package com.xhb.campusservices.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮箱验证
 */
@Repository
public class Smtp {

     @Autowired
     JavaMailSenderImpl mailSender;

    public  void sendMail(String email){
        //组装
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper  = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom("互助帮<2919858998@qq.com>");
            helper.setSubject("验证您的 互助帮 账号");
            String num = getRandNumber();
            helper.setText("<h2 style='display:inline'>互助帮</h2> 稳定、高速、方便地校园服务！<hr/>感谢您注册 互助帮，为了防止我们的服务被滥用，我们需要对您的电子邮件账号进行验证，" +
                    "您只在注册页面输入以下数字即可验证。验证码有效期为 15 分钟，请尽快完成注册。\n" +"<h3>"+num+"</h3> \n" +
                    "此邮件由系统自动发送，请勿直接回复，如果您没有注册过本站账号，请无视此邮件。<hr/> <p style='text-align:right'>互助帮</p>",true);
            //发送到这个邮箱
            helper.setTo(email);
            this.mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    /**
     * 生成随机数
     * @return
     */
    public static String getRandNumber() {
        StringBuffer numStr = new StringBuffer();
        int num;
        for (int i = 0; i < 6; i++) {
            // Math.random() 随机出0-1之间的实数，返回值是⼀个double 类型的
            num = (int) (Math.random() * 10);
            numStr.append(String.valueOf(num));
        }
        return numStr.toString();
    }
}
